/**
 *
 * @author pquiring
 *
 * Created : Jan 15, 2014
 */

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javaforce.JF;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MainPanel extends javax.swing.JPanel implements KeyEventDispatcher {

  /**
   * Creates new form MainPanel
   */
  public MainPanel() {
    initComponents();
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
    This = this;
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    tabs = new javax.swing.JTabbedPane();
    jToolBar1 = new javax.swing.JToolBar();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    jToolBar1.setFloatable(false);
    jToolBar1.setRollover(true);

    jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/play.png"))); // NOI18N
    jButton1.setFocusable(false);
    jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });
    jToolBar1.add(jButton1);

    jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/stop.png"))); // NOI18N
    jButton2.setFocusable(false);
    jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
      }
    });
    jToolBar1.add(jButton2);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(tabs, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(tabs, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.playSong();
  }//GEN-LAST:event_jButton1ActionPerformed

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.stopSong();
  }//GEN-LAST:event_jButton2ActionPerformed


  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JToolBar jToolBar1;
  private javax.swing.JTabbedPane tabs;
  // End of variables declaration//GEN-END:variables

  public static String currentPath = JF.getUserPath() + "/Music";
  public static MainPanel This;

  public void newSong() {
    SongPanel song = new SongPanel();
    tabs.add(song, "Untitled");
  }

  public void open() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("Music Files (*.mproj)", "mproj"));
    chooser.setFileFilter(chooser.getChoosableFileFilters()[1]);  //use first added filefilter added
    chooser.setMultiSelectionEnabled(false);
    chooser.setCurrentDirectory(new File(currentPath));
    if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
    File file = chooser.getSelectedFile();
    currentPath = file.getParent();
    if (currentPath == null) currentPath = JF.getUserPath() + "/Music";
    String fn = file.getAbsolutePath();
    if (!fn.toLowerCase().endsWith(".mproj")) fn += ".mproj";
    SongPanel song = new SongPanel();
    if (!song.load(fn)) return;
    String name = file.getName();
    tabs.add(song, name.substring(0, name.length() - 6));
  }

  public void save() {
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.save();
  }

  public void close() {
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.close();
    tabs.remove(panel);
  }

  private SongPanel getSongPanel(JComponent src) {
    if (src instanceof SongPanel) return (SongPanel)src;
    Object parent = src.getParent();
    if (parent == null) return null;
    if (!(parent instanceof JComponent)) return null;
    return getSongPanel((JComponent)parent);
  }

  public boolean dispatchKeyEvent(KeyEvent e) {
    Object awtsrc = e.getSource();
    if (!(awtsrc instanceof JComponent)) return false;
    JComponent src = (JComponent)awtsrc;
    SongPanel panel = getSongPanel(src);
    if (panel == null) return false;
    int id = e.getID();
    char ch = e.getKeyChar();
    int cc = e.getKeyCode();
    switch (id) {
      case KeyEvent.KEY_TYPED:
        break;
      case KeyEvent.KEY_PRESSED:
        switch (cc) {
          case KeyEvent.VK_F1: panel.selectTab(0); break;
          case KeyEvent.VK_F2: panel.selectTab(1); break;
          case KeyEvent.VK_F3: panel.selectTab(2); break;
          case KeyEvent.VK_F4: panel.selectTab(3); break;
        }
        break;
      case KeyEvent.KEY_RELEASED:
        break;
    }
    return false;
  }

  public void setTitle(SongPanel panel, String title) {
    for(int a=0;a<tabs.getTabCount();a++) {
      if (tabs.getComponentAt(a) == panel) {
        tabs.setTitleAt(a, title);
        break;
      }
    }
  }

  public void insertRow() {
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.insertRow();
  }

  public void deleteRow() {
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.deleteRow();
  }

  public void dupPattern() {
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.dupPattern();
  }

  public void export() {
    SongPanel panel = (SongPanel)tabs.getSelectedComponent();
    if (panel == null) return;
    panel.export();
  }
}
